import React, {  useEffect, useRef, useState } from 'react'
import { AlertTip } from 'src/components'
import './index.scss'

const ComputeTime = (props) => {
    const { time } = props;
    const [countNum, setCountNum] = useState(900)
    const [showAlert, setShowAlert] = useState(false)
    const [alertText, setAlertText] = useState()
    const timerRef = useRef()




    useEffect(() => {
        //订单返回时间秒分分别处理
        const numTime = () => {
            if (time.toString().indexOf('分钟') !== -1) {
                return parseInt(time) * 60;
            } else {
                return parseInt(time);
            }
        }
        setCountNum(countNum - numTime())
        //计算时间
        const remainingTime = () => {
            clearInterval(timerRef.current);
            timerRef.current = setInterval(() => {
                setCountNum(countNum - 1)
                if (countNum === 0) {
                    clearInterval(timerRef.current);
                    setShowAlert(true)
                    setAlertText('支付超时')
                }
            }, 1000);
        }
        remainingTime();
    }, [countNum, time])

    //转换时间成分秒
    const remaining = () => {
        let minute = parseInt(countNum / 60);
        let second = parseInt(countNum % 60);
        if (minute < 10) {
            minute = '0' + minute;
        }
        if (second < 10) {
            second = '0' + second;
        }
        return '去支付(还剩' + minute + '分' + second + '秒)';
    }

    const handleCloseTip = () => {
        setShowAlert(false)
    }

    const gotoPay = () => {
        setShowAlert(true)
        setAlertText('暂不开放支付接口')
    }

    return <div className="page">
        <span className="rem_time" onClick={gotoPay}>
            {remaining()}
        </span>
        {showAlert && <AlertTip onClose={handleCloseTip} alertText={alertText}></AlertTip>}
    </div>
}

export default ComputeTime